package com.example.my_music_palyer.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误处理控制器
 */
@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public Map<String, Object> handleError(HttpServletRequest request) {
        Map<String, Object> errorInfo = new HashMap<>();
        
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String errorMessage = (String) request.getAttribute("javax.servlet.error.message");
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        String exceptionType = (String) request.getAttribute("javax.servlet.error.exception_type");
        Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
        
        errorInfo.put("timestamp", System.currentTimeMillis());
        errorInfo.put("status", statusCode);
        errorInfo.put("error", errorMessage != null ? errorMessage : "未知错误");
        errorInfo.put("path", requestUri);
        errorInfo.put("exception", exceptionType);
        
        if (exception != null) {
            errorInfo.put("message", exception.getMessage());
            errorInfo.put("stackTrace", getStackTrace(exception));
        }
        
        return errorInfo;
    }

    private String getStackTrace(Throwable throwable) {
        StringBuilder sb = new StringBuilder();
        for (StackTraceElement element : throwable.getStackTrace()) {
            sb.append(element.toString()).append("\n");
        }
        return sb.toString();
    }
}
